package com.chanceit.ssss.activity;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.gl.GlobalVariable;
import org.gl.ui.manger.BaseActivity;
import org.gl.utils.AndroidUtil;
import org.gl.utils.lg;
import org.json.JSONException;
import org.json.JSONObject;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.chanceit.ssss.common.ActivityActionName;
import com.chanceit.ssss.common.IntentExtraDataKey;
import com.chanceit.ssss.common.WebServicUrl;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class PasswordActivity extends BaseActivity implements OnClickListener {
	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;
	private String mPassword_new;
	private String mPassword_repeate;

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private EditText mNewPasswordView;
	private EditText mReNewPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private CheckBox chechBox_rember;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_password);
		chechBox_rember = (CheckBox) findViewById(R.id.checkBox_rember);
		// Set up the login form.
		mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		String[] mAccountInfo = AndroidUtil.getAccountPassword();
		if (mEmail == null) {
			mEmail = mAccountInfo[0];
			if (!TextUtils.isEmpty(mEmail)) {
				chechBox_rember.setChecked(true);
			}
		}

		mEmailView = (EditText) findViewById(R.id.account);
		mEmailView.setText(mEmail);
		mPasswordView = (EditText) findViewById(R.id.oldpassword);
		mNewPasswordView = (EditText) findViewById(R.id.newpassword);
		mReNewPasswordView = (EditText) findViewById(R.id.repeatnewpassword);

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		chechBox_rember
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton arg0,
							boolean arg1) {
						if (arg1) {

						}
					}
				});
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			// TODO: If Settings has multiple levels, Up should navigate up
			// that hierarchy.
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptUpdatePassword() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();
		mPassword_new = mNewPasswordView.getText().toString();
		mPassword_repeate = mReNewPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		}
		if (TextUtils.isEmpty(mPassword_new)) {
			mNewPasswordView.setError(getString(R.string.error_field_required));
			focusView = mNewPasswordView;
			cancel = true;
		}
		if (TextUtils.isEmpty(mPassword_repeate)) {
			mReNewPasswordView
					.setError(getString(R.string.error_field_required));
			focusView = mReNewPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		}
		if (!mPassword_repeate.equals(mPassword_new)) {
			mReNewPasswordView
					.setError(getString(R.string.passord_repeatnewnosame));
			focusView = mReNewPasswordView;
			cancel = true;
		}
		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		int isfinish = 0;
		final int err_passowrd = 2;
		final int err_server = 500;
		final int err_no = 200;

		@Override
		protected Boolean doInBackground(Void... params) {
			HttpPost post = new HttpPost(WebServicUrl.login);
			List<BasicNameValuePair> par = new ArrayList<BasicNameValuePair>();
			par.add(new BasicNameValuePair("account", mEmail));
			par.add(new BasicNameValuePair("password", mPassword));
			try {
				post.setEntity(new UrlEncodedFormEntity(par, HTTP.UTF_8));

				HttpResponse mHttpResponse = GlobalVariable.DefaultHttpClient
						.execute(post);
				isfinish = mHttpResponse.getStatusLine().getStatusCode();
				if (isfinish == 200) {
					InputStream is = mHttpResponse.getEntity().getContent();
					byte bytes[] = new byte[1024 * 4];
					StringBuilder sb = new StringBuilder();
					int x;
					while ((x = is.read(bytes)) != -1) {
						sb.append(new String(bytes, 0, x));
					}
					lg.i(TAG, sb.toString());
					JSONObject json_result = new JSONObject(sb.toString());
					isfinish = json_result.optInt("code");
					if (isfinish == 0) {
						isfinish = err_no;
						GlobalVariable.getGlobalInstance().intent.putExtra(
								IntentExtraDataKey.ACCOUNE_ID,
								json_result.optInt("accountId"));

						post = new HttpPost(WebServicUrl.account_set);
						par = new ArrayList<BasicNameValuePair>();
						par.add(new BasicNameValuePair("oldPassword", mPassword));
						par.add(new BasicNameValuePair("password",
								mPassword_repeate));
						post.setEntity(new UrlEncodedFormEntity(par, HTTP.UTF_8));
						mHttpResponse = GlobalVariable.DefaultHttpClient
								.execute(post);
						is = mHttpResponse.getEntity().getContent();
						bytes = new byte[1024 * 4];
						sb = new StringBuilder();
						while ((x = is.read(bytes)) != -1) {
							sb.append(new String(bytes, 0, x));
						}
						lg.i(TAG, sb.toString());
						json_result = new JSONObject(sb.toString());
						isfinish = json_result.optInt("code");
						if (isfinish==err_server||isfinish==err_passowrd) {
							isfinish = err_server;
						}else{
							isfinish =err_no;
						}
					} else {
						isfinish = err_passowrd;
					}
				} else {
					throw new IOException("fail,servers errcode:" + isfinish);
				}
			} catch (UnsupportedEncodingException e1) {
				isfinish =err_server;
				e1.printStackTrace();
			} catch (ClientProtocolException e) {
				isfinish =err_server;
				e.printStackTrace();
			} catch (IOException e) {
				isfinish =err_server;
				e.printStackTrace();
			} catch (JSONException e) {
				isfinish =err_server;
				e.printStackTrace();
			}
			return (isfinish == err_no) ? true : false;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			showProgress(false);

			if (success) {
				startActivity(new Intent(ActivityActionName.HOME));
				finish();
			} else {
				chechBox_rember.setChecked(false);
				if (isfinish == err_passowrd) {
					mPasswordView
							.setError(getString(R.string.error_incorrect_password));
					mPasswordView.requestFocus();
				}else if(isfinish ==err_server){
					mReNewPasswordView.setError(getString(R.string.err_server));
					mReNewPasswordView.requestFocus();
				}

			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_passowrd_update:
			startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.PASSWORD));
			break;
		case R.id.iv_setting:
			startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.SETTING));
			break;
		case R.id.password_button:
			attemptUpdatePassword();
			break;
		default:
			break;
		}

	}
}
